
import { useMemo, useState } from 'react';
import styles from './index.less';
import { Editor } from '@bytemd/react'
import gfm from '@bytemd/plugin-gfm';
//高亮代码块
import highlight from '@bytemd/plugin-highlight';
import 'highlight.js/styles/default.css';
import 'bytemd/dist/index.css'//引入编辑器样式
import zhHans from "bytemd/lib/locales/zh_Hans.json";// 引入中文包
import "highlight.js/styles/github.css";// 引入高亮css
// import "juejin-markdown-themes/dist/juejin.min.css";//引入掘金主题
import mediumZoom from '@bytemd/plugin-medium-zoom';// 缩放图片
import frontmatter from '@bytemd/plugin-frontmatter';// 解析前题
import breaks from '@bytemd/plugin-breaks'; //回车换行
import { Button, Input, Space,Drawer, Form, Row, Col, Select, message } from 'antd';
// import 'juejin-markdown-themes/dist/scrolls-light.min.css'
// import 'juejin-markdown-themes/dist/channing-cyan.min.css'
import Uploads from '@/components/Uploads';
import themePlugin from './Themes';

import themes from 'juejin-markdown-themes';
import { getArticleType, uploadFile } from '@/services/commonServices';
import { history, run, useRequest } from '@umijs/max';
import { editArticle, getArticleDetail } from '@/services/article';
import { set } from 'lodash';
import { filterSensitiveWord, getImgUrl, makeSensitiveMap } from '@/utils';
import useSearchParams from '@/hooks/useSearchParams';


const { Option } = Select;


export default () => {
    const {articleId} = useSearchParams();
    const txt = articleId ?'更新':'发布';
    const [form] = Form.useForm();
    const [content, setContent] = useState('')
    const [title,setTitle] = useState('');
    const [open,setOpen] = useState(false);
    const plugins = [
      gfm(),
      highlight(),
      mediumZoom(),
      frontmatter(),
      breaks(),
      themePlugin(setContent),
  ]
  const {run:edit }= useRequest(editArticle,{
    manual: true,
    onSuccess: (res) => {
      message.success(txt+'成功,请耐心等待管理员审核')
      history.push('/creator')
    }
  })

    const  uploadImage = async(files) => {
        const res = await upload(files)
        return [
            {
                title: files.map((i) => i.name),
                url: res,
            },
        ]
    }
    //图片上传到服务器
    const upload = async(files:File[]) => {
        const res = await uploadFile(files[0])
        return getImgUrl(res)
    }
     // 状态：0：草稿箱，1：待审核，2：已发布，3：驳回
    const save = async(status:number) =>{
      const formVal = status===0 ?(await form.getFieldsValue()) :(await form.validateFields());
      if(!title.trim()){
        return message.error('请填写文章标题')
      }
      if(!content.trim()){
        return message.error('请填写文章内容')
      }
      const params = {
        content,
        status,
        title,
        tags:'',
        ...formVal,
      }
      if(formVal?.images?.[0]){
        params.images = formVal?.images?.[0]
      }

      if(articleId){
        params.id = articleId
      }
      edit(params)
      setOpen(false);
    }
      // const test = filterSensitiveWord(content,makeSensitiveMap(['前端','前端的',"日本鬼子",'sb','网页',"优化"]))

    const onClose = () => {
      setOpen(false);
    };
    useRequest(getArticleDetail,{
      manual:!articleId,
      defaultParams:[articleId],
      onSuccess:(res)=>{
        setTitle(res.title)
        setContent(res.content)
        form.setFieldsValue({
          type:res.type,
          summary:res.summary,
          images:[res.images],
          tags:res.tags,
        })
      }
    })
const {data:articleType}=  useRequest(getArticleType)
const menuItems = useMemo(()=>{
  const arr = articleType?.map?.((item)=>{
    return {
      label:item.name,
      value:item.name,
    }
  })||[]
  return arr
},[articleType])

    return <div className={styles.container}>
        <div className={styles.top}>
            <Input className={styles.titleInput} value={title} onChange={(e)=>setTitle(e.target.value)}  placeholder='输入标题...' />
            <div className={styles.rightBox}>
                <Button onClick={()=>{save(0)}}>草稿箱</Button>
                <Button type='primary' onClick={()=>{
                    setOpen(true)
                }}>{txt}</Button>
            </div>
        </div>
        <div className={styles.edit}>
            <Editor
                value={content}
                plugins={plugins}
                onChange={(v) => {
                    setContent(v)
                }}
                locale={zhHans}
                uploadImages={uploadImage}
            />
        </div>
        <Drawer
        title={txt+'文章'}
        width={560}
        onClose={onClose}
        open={open}
        styles={{
          body: {
            paddingBottom: 80,
          },
        }}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button onClick={()=>save(1)} type="primary">
              确认
            </Button>
          </Space>
        }
      >
         <Form form={form} >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="type"
                label="分类"
                // rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类" options={menuItems} />
              </Form.Item>
            </Col>
          </Row>
          {/* <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="tags"
                label="标签"
                // rules={[{ required: true, message: '请选择标签' }]}
              >
                <Select placeholder="请选择标签" options={menuItems} mode='multiple' />
              </Form.Item>
            </Col>
          </Row> */}
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="images"
                label="封面"
              >
               <Uploads length={1} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="summary"
                label="摘要"
                rules={[
                  {
                    required: true,
                    message: '请输入摘要',
                  },
                ]}
                initialValue={''}
              >
                <Input.TextArea showCount maxLength={100} rows={4} placeholder="" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
    </div>
}